package com.group.voting_system.service.impl;

import com.group.voting_system.entity.Vote;
import com.group.voting_system.mapper.VoteMapper;
import com.group.voting_system.service.IVoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.voting_system.utils.DateUtil;
import com.group.voting_system.utils.QRUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyf
 * @since 2019-04-15
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {

    @Resource
    VoteMapper voteMapper;

    @Value("${localQR.path}")
    String path;

    @Value("${localQR.logo}")
    String logo;

    @Override
    public Boolean addOneVote(Vote vote, HttpServletRequest request) {
        //将设置时间放入
        vote.setSetTime(DateUtil.getNowDate());
        int insert = voteMapper.addVote(vote);
        if (insert == 1){
            //创建二维码
            String content = request.getScheme()+"://"
                    + request.getServerName() +":"
                    + request.getServerPort() + "/user/vote/"
                    + vote.getId();
            QRUtil.createCode(vote.getId().toString(), content, path, 500, logo);
        }
        return insert == 1;
    }

    @Override
    public Integer getAllPoll(Integer vid) {
        Integer poll = voteMapper.getAllPoll(vid);
        return poll;
    }

    @Override
    public Integer getUserCount(Integer vid) {
        Integer userCount = voteMapper.getUserCount(vid);
        return userCount;
    }

    @Override
    public Integer getLeftDays(Integer vid) {
        Vote vote = voteMapper.selectById(vid);
        Integer leftDays = Math.toIntExact((vote.getEndTime().getTime() - vote.getStartTime().getTime()) / (1000 * 24 * 3600));
        return leftDays;
    }
}
